﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;

namespace Identity.API
{
    public static class Certificate
    {
        public static IIdentityServerBuilder AddIdentityServerSigningCredential(this IIdentityServerBuilder builder, IConfiguration configuration)
        {
            var assembly = typeof(Certificate).GetTypeInfo().Assembly;

            using var stream = assembly.GetManifestResourceStream("Identity.API.Certificate.idsrv4.pfx");
            using var ms = new MemoryStream();
            var buffer = new byte[16 * 1024];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }

            builder.AddSigningCredential(new X509Certificate2(ms.ToArray(), configuration["Certificate:Password"]));

            return builder;
        }
    }
}
